import Cookies from "js-cookie";
import {addCartApi, addOrderApi, delCartApi, getCartApi} from "@/network/api";
import {getTokenId} from "@/common/auth";


export function getDish(id) {
    let regex = /^food_/;
    if (!regex.test(id)) {
        id = "food_" + id
    }
    return JSON.parse(Cookies.get(id))
}

export function getDishNumber(id) {
    id = "food_" + id
    if (Cookies.get(id) === undefined) return 0
    return JSON.parse(Cookies.get(id)).number
}

export function setDish(id, food) {
    isChange = true
    if (food.businessId.toString() === getBusinessId() || getBusinessId() === "-1") {
        setBusinessId(food.businessId)

        id = "food_" + id
        return Cookies.set(id, JSON.stringify(food))
    } else {
        uni.showToast({
            title: '不可跨店添加',
            icon: 'none',    //如果要纯文本，不要icon，将值设为'none'
            duration: 2000    //持续时间为 2秒
        })
        return false
    }


}

export function removeDish(id) {
    // delCartApi({dishid: id, userid: getTokenId()}).then(r => {
    // })
    id = "food_" + id
    isChange = true
    return Cookies.remove(id)
}

let isChange = true

//是否可操作

export function handleChange(food) {

    if (getOrders().length === 0) {
        setBusinessId(-1)
    }
    if (isChange) {
        isChange = false
        // 处理选择器数值变化事件
        if (food.number === 0) {
            removeDish(food.id)
        } else {
            setDish(food.id, food)
        }
    } else {
        uni.showToast({
            title: '操作太快',
            icon: 'none',    //如果要纯文本，不要icon，将值设为'none'
            duration: 2000    //持续时间为 2秒
        })
        return false
    }
}

export function pushCart() {
    uni.switchTab({
        url: '../order/order'
    });
}


export function getOrders() {
    const strCookie = document.cookie;
    const arrCookie = strCookie.split("; ");
    let list = []
    // getCartApi().then(res => {
    //     return list = res.data
    // })
    for (let i = 0; i < arrCookie.length; i++) {
        let arr = arrCookie[i].split("=");
        let regex = /^food_/;
        if (regex.test(arr[0])) {
            //console.log("表示数组中含有此字符串")
            list.push(getDish(arr[0]))
        }
    }
    return list || []
}


export function removeAll() {
    setBusinessId(-1)
    const strCookie = document.cookie;
    const arrCookie = strCookie.split("; ");
    let list = []
    for (let i = 0; i < arrCookie.length; i++) {
        let arr = arrCookie[i].split("=");
        let regex = /^food_/;
        if (regex.test(arr[0])) {
            //console.log("表示数组中含有此字符串")
            //list.push(getDish(arr[0]))
            //console.log(arr[0])
            Cookies.remove(arr[0])
        }
    }
    return list
}


// 计算商品总价格
export function getOrdersTotal() {
    return getOrders().reduce((acc, product) => acc + (product.price * product.number), 0);
}

export function toDish(dish) {
    console.log(dish)
    uni.navigateTo({
        url: '/pages/dish/dish?dish=' + JSON.stringify(dish) + '&shopId=' + this.shopId
    });
}

export function getStatusText(status) {
    // You can customize this method to display meaningful status text
    switch (status.toString()) {////订单状态 1已付款，2已出餐待派送，3已接单，4已派送，5已完成，6已取消
        case '1':
            return '已付款';
        case '2':
            return '待派送';
        case '3':
            return '已接单';
        case '4':
            return '已派送';
        case '5':
            return '已完成';
        case '6':
            return '已取消';
        case '7':
            return '已结束';
        default:
            return '未知状态';
    }
}

export function getNowTime() {
    const currentDate = new Date();

    const year = currentDate.getFullYear();
    const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
    const day = currentDate.getDate().toString().padStart(2, '0');
    const hour = currentDate.getHours().toString().padStart(2, '0');
    const minute = currentDate.getMinutes().toString().padStart(2, '0');
    const second = currentDate.getSeconds().toString().padStart(2, '0');

    const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`;


    console.log("当前时间为：" + formattedDate);
    return formattedDate;
}


const businessKey = 'businessKey_take_out'

export function setBusinessId(id) {
    return Cookies.set(businessKey, id)
}

export function getBusinessId() {
    return Cookies.get(businessKey) || '-1';
}